package com.lizhangjun.nim.controller;

import com.alibaba.fastjson.JSON;
import com.lizhangjun.nim.constant.*;
import com.lizhangjun.nim.entity.Result;
import com.lizhangjun.nim.push.Publisher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.security.PermitAll;
import java.util.ArrayList;
import java.util.List;

/**
 * IM消息发送接口
 * @author lizhangjun
 * @since 2020-08-27
 */
@Slf4j
@RestController
@RequestMapping("/v1/im")
public class ImController {

    @Autowired
    private Publisher publisher;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 单播/组播
     * toUserId 目标id
     * toGroupId 用户组id
     * content 消息内容
     * @param iMessage 消息体
     * @return 信息结果
     */
    @PermitAll
    @PostMapping("/send")
    public Result send(@RequestBody IMessage iMessage){
        //String fromUserId = Jwt.getClaim(authorization, "userId");
        //消息体
        IMessage msg;
        //消息集合（toUserId可能有多个）
        List<IMessage> messageList = new ArrayList<>();
        if (StringUtils.isNotBlank(iMessage.getToGroupId())){
            //组播
            msg = new IMessage.Builder(Flag.OK)
                    .fromUserId(iMessage.getFromUserId())
                    .toUserId(iMessage.getToUserId())
                    .toGroupId(iMessage.getToGroupId())
                    .mineType(MineType.TEXT.getIndex())
                    .chatType(ChatType.MULTICAST.getIndex())
                    .msgType(MsgType.CHAT.getIndex())
                    .content(iMessage.getContent())
                    .extras(iMessage.getExtras())
                    .build();
            //保存记录
            messageList.add(iMessage);
        }else {
            //单播
            msg = new IMessage.Builder(Flag.OK)
                    .fromUserId(iMessage.getFromUserId())
                    .toUserId(iMessage.getToUserId())
                    .mineType(MineType.TEXT.getIndex())
                    .chatType(ChatType.UNICAST.getIndex())
                    .msgType(MsgType.CHAT.getIndex())
                    .content(iMessage.getContent())
                    .extras(iMessage.getExtras())
                    .build();
            //保存记录
            String[] split = iMessage.getToUserId().split(SystemConstant.DEFAULT_REGEX);
            if (split.length > 0){
                for (String e : split){
                    iMessage.setToUserId(e);
                    messageList.add(iMessage);
                }
            }
        }

        //持久化
        mongoTemplate.insertAll(messageList);
        publisher.run(JSON.toJSONString(msg));
        return Result.ok(msg);
    }

    /**
     * 广播
     * content 消息内容
     * @param iMessage 消息体
     * @return 信息结果
     */
    @PermitAll
    @PostMapping("/common/send")
    public Result commonSend(@RequestBody IMessage iMessage){
        IMessage msg = new IMessage.Builder(Flag.OK)
                .fromUserId("common")
                .toUserId("common")
                .toGroupId("broadcast")
                .mineType(MineType.TEXT.getIndex())
                .chatType(ChatType.BROADCAST.getIndex())
                .msgType(MsgType.CHAT.getIndex())
                .content(iMessage.getContent())
                .extras(iMessage.getExtras())
                .build();
        //持久化
        mongoTemplate.save(msg);
        publisher.run(JSON.toJSONString(msg));
        return Result.ok(msg);
    }
}
